import { useEffect, useRef, useState } from "react";
import { Button, Card, Drawer, Form, Input, Space, Select, Spin, Tabs } from "antd";
import type { ColumnsType } from "antd/es/table";
import stockInService, { type PageListReq } from "@/api/services/wms/stockInService";
import type { WmsStockIn } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";
import WmsStockInDetailPage, { type WmsStockInDetailHandles } from "./detail";
import CustomTable from "@/components/grid/CustomTable";

const { TextArea } = Input;

export default function WmsStockInPage() {
	const stockInDetailRef = useRef<WmsStockInDetailHandles>(null);

	const [loading, setLoading] = useState(false);
	const [submitLoading, setSubmitLoading] = useState(false);
	const [queryParams, setQueryParams] = useState<PageListReq>({
		code: undefined,
		sourceCode: undefined,
		type: undefined,
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);
	const [list, setList] = useState<WmsStockIn[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [drawerVisible, setDrawerVisible] = useState(false);
	const [editingData, setEditingData] = useState<WmsStockIn | null>(null);
	const [form] = Form.useForm();
	const [isView, setIsView] = useState(true);

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 405;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	const typeOptions = useDictionary("stock_in_type");
	const statusOptions = useDictionary("stock_in_status");

	const columns: ColumnsType<WmsStockIn> = [
		{
			title: "入库单编码",
			width: 120,
			key: "code",
			dataIndex: "code",
		},
		{
			title: "来源单号",
			width: 120,
			key: "sourceCode",
			dataIndex: "sourceCode",
		},
		{
			title: "入库单类型",
			width: 120,
			key: "type",
			dataIndex: "type",
			render: (_, record) => <TableDictTag dictCode="stock_in_type" value={record.type ?? ""} />,
		},
		{
			title: "仓库ID",
			width: 120,
			key: "warehouseId",
			dataIndex: "warehouseId",
		},
		{
			title: "状态",
			width: 120,
			key: "status",
			dataIndex: "status",
			render: (_, record) => <TableDictTag dictCode="stock_in_status" value={record.status ?? ""} />,
		},
		{
			title: "操作",
			fixed: "right",
			key: "operation",
			align: "center",
			width: 100,
			render: (_, record) => (
				<Space>
					<Button type="link" onClick={() => handleView(record)}>
						{t("common.view")}
					</Button>
					<Button type="link" onClick={() => handleEdit(record)}>
						{t("common.edit")}
					</Button>
				</Space>
			),
		},
	];

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		stockInService
			.pageList(queryParams)
			.then((res) => {
				setList(res.records);
				setTotal(res.total);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchPageList();
	}, [queryParams]);

	//选择其他页
	const handlePageChange = (newPage: number, newPageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page: newPage,
			pageSize: newPageSize,
		}));
	};

	//触发编辑按钮
	const handleEdit = (wmsStockIn: WmsStockIn) => {
		setEditingData(wmsStockIn);
		form.setFieldsValue(wmsStockIn);
		setDrawerVisible(true);
		setIsView(false);
	};

	//触发视图按钮
	const handleView = (wmsStockIn: WmsStockIn) => {
		setEditingData(wmsStockIn);
		form.setFieldsValue(wmsStockIn);
		setIsView(true);
		setDrawerVisible(true);
	};

	//提交表单数据
	const handleSubmit = async (values: WmsStockIn) => {
		try {
			setSubmitLoading(true);

			//入库单明细
			const deleteStockInDetailIds = stockInDetailRef.current?.getDeleteIds();
			const addStockInDetails = stockInDetailRef.current?.getAddList();
			const updateStockInDetails = stockInDetailRef.current?.getUpdateList();

			const data = {
				...values,
				id: editingData?.id,
				deleteStockInDetailIds: deleteStockInDetailIds,
				addStockInDetails: addStockInDetails,
				updateStockInDetails: updateStockInDetails,
			};
			if (editingData) {
				await stockInService.update(data);
				toast.success("更新入库单成功");
			} else {
				await stockInService.add(data);
				toast.success("创建入库单成功");
			}
			setDrawerVisible(false);
			setEditingData(null);
			form.resetFields();
			fetchPageList();
		} catch (error) {
			toast.error(`保存失败: ${error.message}`);
		} finally {
			setSubmitLoading(false);
		}
	};

	const handleDrawerClose = () => {
		setDrawerVisible(false);
		setEditingData(null);
		form.resetFields();
	};

	const handleAdd = () => {
		setEditingData(null);
		form.resetFields();
		setDrawerVisible(true);
		setIsView(false);
	};

	const handleDelete = async () => {
		try {
			setLoading(true);
			await stockInService.remove(selectedRowKeys);
			toast.success("删除入库单成功");
			setSelectedRowKeys([]);
			fetchPageList();
		} catch (error) {
			toast.error(`删除失败: ${error.message}`);
		} finally {
			setLoading(false);
		}
	};

	return (
		<Spin spinning={submitLoading} tip="数据提交中..." size="large">
			<Card className="mb-4">
				<Form
					layout="inline"
					style={{ display: "flex", flexWrap: "wrap", gap: "16px" }}
					labelCol={{ span: 8 }}
					wrapperCol={{ span: 16 }}
					onFinish={(values) => {
						setQueryParams((prev) => ({
							...prev,
							...values,
							page: 1,
						}));
					}}
				>
					<Form.Item name="code" label="入库单编码" style={{ width: 250 }}>
						<Input allowClear placeholder="请输入入库单编码" />
					</Form.Item>

					<Form.Item name="sourceCode" label="来源单号" style={{ width: 250 }}>
						<Input allowClear placeholder="请输入来源单号" />
					</Form.Item>

					<Form.Item name="type" label="入库单类型" style={{ width: 250 }}>
						<Select options={typeOptions} allowClear style={{ width: 170 }} placeholder="请选择入库单类型" />
					</Form.Item>

					<Form.Item style={{ width: 250, marginLeft: 15 }}>
						<Button type="primary" htmlType="submit">
							查询
						</Button>
						<Button
							className="ml-2"
							onClick={() => {
								setQueryParams({ page: 1, pageSize: 10 });
							}}
						>
							重置
						</Button>
					</Form.Item>
				</Form>
			</Card>
			<div className="h-4" />
			<Card>
				<CustomTable
					loading={loading}
					columnsConfig={columns}
					dataSource={list}
					total={total}
					selectedRowKeys={selectedRowKeys}
					setSelectedRowKeys={setSelectedRowKeys}
					current={queryParams.page}
					pageSize={queryParams.pageSize}
					onRefresh={fetchPageList}
					onPageChange={handlePageChange}
					selectable
					toolbarButtons={
						<>
							<Button type="primary" onClick={handleAdd}>
								新增
							</Button>
							<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
								删除
							</Button>
						</>
					}
					scroll={{ y: tableScrollY }}
				/>
			</Card>
			<Drawer
				title={editingData ? "编辑入库单" : "新增入库单"}
				width={800}
				open={drawerVisible}
				onClose={handleDrawerClose}
				footer={
					<div className="flex justify-end gap-2">
						<Button onClick={handleDrawerClose}>取消</Button>
						{!isView && (
							<Button type="primary" loading={submitLoading} onClick={() => form.submit()}>
								确定
							</Button>
						)}
					</div>
				}
			>
				<Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} onFinish={handleSubmit} disabled={isView}>
					<Form.Item
						name="code"
						label="入库单编码"
						rules={[
							{
								required: true,
								message: "请填写入库单编码",
							},
						]}
					>
						<Input placeholder="请输入入库单编码" allowClear />
					</Form.Item>

					<Form.Item name="sourceCode" label="来源单号">
						<Input placeholder="请输入来源单号" allowClear />
					</Form.Item>

					<Form.Item name="type" label="入库单类型">
						<Select options={typeOptions} allowClear />
					</Form.Item>

					<Form.Item
						name="warehouseId"
						label="仓库ID"
						rules={[
							{
								required: true,
								message: "请填写仓库ID",
							},
						]}
					>
						<Input placeholder="请输入仓库ID" allowClear />
					</Form.Item>

					<Form.Item
						name="status"
						label="状态"
						rules={[
							{
								required: true,
								message: "请填写状态",
							},
						]}
					>
						<Select options={statusOptions} allowClear />
					</Form.Item>

					<Form.Item name="remark" label="备注">
						<TextArea />
					</Form.Item>

					<Tabs
						defaultActiveKey="1"
						items={[
							{
								key: "1  ",
								label: "入库单明细",
								children: <WmsStockInDetailPage ref={stockInDetailRef} parentId={editingData?.id} />,
							},
						]}
					/>
				</Form>
			</Drawer>
		</Spin>
	);
}
